package cn.alm.springmvcrestfulcrud.advice;

import cn.alm.springmvcrestfulcrud.common.CR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public CR handleException(Exception e) {
        log.info("异常类型为：" + e.getClass().getName());
        e.printStackTrace();
        return CR.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CR handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<FieldError> fieldErrors = e.getFieldErrors();
        HashMap<String, String> errMap = new HashMap<>();
        for (FieldError fieldError : fieldErrors) {
            errMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        }
        return CR.create(500, "校验失败", errMap);
    }

}
